{% block content %}

<!-- 引入Bootstrap CSS和JS -->
<link href='{% static "bootstrap/bootstrap.min.css" %}' rel='stylesheet'>
<script src='{% static "bootstrap/jquery-3.6.0.min.js" %}'></script>
<script src='{% static "bootstrap/bootstrap.bundle.min.js" %}'></script>
<script src='{% static "fullcalendar/index.global.min.js" %}'></script>
<script src='{% static "fullcalendar/zh-cn.global.min.js" %}'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js'></script>
<link rel='stylesheet' href='{% static "fullcalendar/fullcalendar.min.css" %}'>
<link rel='stylesheet' href='{% static "css/fullcalendar_styles.css" %}'>
<link rel='stylesheet' href='{% static "bootstrap-icons-1.13.1/font/bootstrap-icons.css" %}'>

<!-- 页面内容 -->
<div class='container mt-4 mb-6'>
   <div class='card rounded-xl overflow-hidden shadow-xl border-0 mb-8'>
      <div class='card-header bg-white border-bottom border-gray-100 px-4 py-3'>
         <h2 class='h5 font-semibold text-gray-800 mb-0'><i class='bi bi-calendar-week me-2'></i>课程安排日历</h2>
      </div>
      <div class='card-body p-0'>
         <div id='calendar' class='w-100'></div>
      </div>
   </div>
</div>
 <!-- 班级课程创建模态框 -->
  <div class='modal fade' id='classCourseModal' tabindex='-1' aria-labelledby='classCourseModalLabel' aria-hidden='true'>
    <div class='modal-dialog modal-lg'>
      <div class='modal-content'>
        <div class='modal-header'>
          <h5 class='modal-title' id='classCourseModalLabel'><i class='bi bi-pencil-square me-2'></i>班级课程安排</h5>
          <button type='button' class='btn-close' data-bs-dismiss='modal' aria-label='Close'></button>
        </div>
        <div class='modal-body'>
          <form id='classCourseForm' >
            {% csrf_token %}
            <input type='hidden' id='classCourseId' name='id'>
            <input type='hidden' name='class_info' value='{{ class_id }}'>
            <div class='mb-3'>
              <label for='class_subject' class='form-label'><i class='bi bi-book me-2'></i>班级学科</label>
              <select id='id_class_subject' name='class_subject' class='form-select rounded-lg border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary/20 transition duration-200'>
                {% for subject in class_subjects %}
                  <option value='{{ subject.id }}'>{{ subject.name }}</option>
                {% endfor %}
              </select>
            </div>
            <div class='mb-3'>
              <label for='weekday' class='form-label'><i class='bi bi-calendar-day me-2'></i>星期几</label>
              <div class='rounded-lg border-gray-300 shadow-sm focus-within:border-primary focus-within:ring focus-within:ring-primary/20 transition duration-200'>
                {{ class_course_form.weekday }}
              </div>
            </div>
            <div class='mb-3'>
              <label for='course_period' class='form-label'><i class='bi bi-clock me-2'></i>课程时间段</label>
              <div class='rounded-lg border-gray-300 shadow-sm focus-within:border-primary focus-within:ring focus-within:ring-primary/20 transition duration-200'>
                {{ class_course_form.course_period }}
              </div>
            </div>
          </form>
        </div>
        <div class='modal-footer'>
          <button type='button' class='btn btn-secondary rounded-lg px-4 py-2' data-bs-dismiss='modal'><i class='bi bi-x-circle me-1'></i>关闭</button>
          <button type='button' class='btn btn-danger rounded-lg px-4 py-2' id='deleteClassCourseBtn' style='display: none;'><i class='bi bi-trash3 me-1'></i>删除</button>
          <button type='button' class='btn btn-primary rounded-lg px-4 py-2' id='saveClassCourseBtn'><i class='bi bi-save me-1'></i>保存</button>
        </div>
      </div>
    </div>
  </div>

<script>
    // *******************设置FullCalendar**************************
  $(document).ready(function() {
      const calendarEl=$('#calendar')[0];
      const calendar=new FullCalendar.Calendar(calendarEl,{
        locale:'zh-cn',
        initialView:'dayGridMonth',
        slotMinTime: '07:00:00',
        slotMaxTime: '23:00:00',
        headerToolbar: {
          left: 'prev,next today addClassCourseBtn',
          center: 'title',
          right: 'dayGridMonth,timeGridWeek,timeGridDay,multiMonthYear'
        },
        customButtons: {
          addClassCourseBtn: {
            text: '添加班级课程',
            icon: 'bi bi-plus-circle',
            click: function() {
              // 清空ID，表示新建
              $('#classCourseId').val('');
              // 隐藏删除按钮
              $('#deleteClassCourseBtn').hide();
              // 显示班级课程安排模态框
              $('#classCourseModal').modal('show');
            }
          }
        },
        views: {
          dayGridMonth: {
            titleFormat: { year: 'numeric', month: 'long' }
          },
          timeGridWeek: {
            titleFormat: { year: 'numeric', month: 'long', week: 'numeric' }
          },
          timeGridDay: {
            titleFormat: { year: 'numeric', month: 'long', day: 'numeric' }
          },
          multiMonthYear: {
            titleFormat: { year: 'numeric' }
          }
        },
        eventSources: [
            {
              url: '{% url 'core:get_course_by_classid' class_id=class_id %}',
              color: 'blue',
              className: 'class-course-event'
            },
             {
              url: '{% url 'core:grade_schedule_by_gradeid' grade_id=grade_id %}',
              color: 'green',
              className: 'grade-schedule-event'
            }
          ],
          // 事件点击处理
          eventClick: function(info) {
            // 处理班级课程事件点击
            classschedule(info);
          },
          // 移除日期点击处理，不再创建年级课程
      });
      calendar.render();

      // 班级课程事件处理函数
      function classschedule(info) {
        // 获取事件ID
        const eventId = info.event.id;
        if (eventId) {
          // 设置ID并显示删除按钮
          $('#classCourseId').val(eventId);
          $('#deleteClassCourseBtn').show();
          // 发送AJAX请求获取事件详情
          $.ajax({
            url: '{% url 'core:get_class_course_detail' pk=0 %}'.replace('0', eventId),
            type: 'GET',
            success: function(data) {
              // 填充表单数据
              $('#id_class_subject').val(data.class_subject);
              $('#id_weekday').val(data.weekday);
              $('#id_course_period').val(data.course_period);
              // 显示模态框
              $('#classCourseModal').modal('show');
            },
            error: function() {
              alert('获取班级课程详情失败');
            }
          });
        } else {
          // 新建事件
          $('#classCourseId').val('');
          $('#deleteClassCourseBtn').hide();
          $('#classCourseModal').modal('show');
        }
      }

      // 保存班级课程
      $('#saveClassCourseBtn').click(function() {
        const formData = $('#classCourseForm').serialize();
        const url = $('#classCourseId').val() ? '{% url 'core:update_class_course' pk=0 %}'.replace('0', $('#classCourseId').val()) : '{% url 'core:class_course_create' %}';
        $.ajax({
          url: url,
          type: 'POST',
          data: formData,
          success: function(response) {
            if (response.status === 'success') {
              // 重新加载日历事件
              calendar.refetchEvents();
              // 关闭模态框
              $('#classCourseModal').modal('hide');
              alert('保存成功');
            } else {
              // 显示错误信息
              let errorMsg = '保存失败: ';
              for (const field in response.errors) {
                errorMsg += '\n' + field + ': ' + response.errors[field].join(' ');
              }
              alert(errorMsg);
            }
          },
          error: function(xhr) {
            try {
              const response = JSON.parse(xhr.responseText);
              let errorMsg = '保存失败: ';
              if (response.errors) {
                for (const field in response.errors) {
                  errorMsg += '\n' + field + ': ' + response.errors[field].join(' ');
                }
              } else {
                errorMsg += response.message || '未知错误';
              }
              alert(errorMsg);
            } catch (e) {
              alert('保存失败: 服务器错误');
            }
          }
        });
      });

      // 删除班级课程
      $('#deleteClassCourseBtn').click(function() {
        if (confirm('确定要删除这个班级课程吗？')) {
          const eventId = $('#classCourseId').val();
          $.ajax({
            url: '{% url 'core:delete_class_course' pk=0 %}'.replace('0', eventId),
            type: 'POST',
            data: {csrfmiddlewaretoken: '{{ csrf_token }}'}, 
            success: function() {
              // 重新加载日历事件
              calendar.refetchEvents();
              // 关闭模态框
              $('#classCourseModal').modal('hide');
              alert('删除成功');
            },
            error: function() {
              alert('删除失败');
            }
          });
        }
      });

      // 阻止默认链接行为
      document.getElementById('create_class_course_btn').addEventListener('click', function(e) {
        e.preventDefault();
        $('#classCourseId').val('');
        $('#deleteClassCourseBtn').hide();
        $('#classCourseModal').modal('show');
      });
  });
</script>
{% endblock %}


